<script>
import { ref,onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request.js'

export default {
  name: 'ResetPassword',
  setup() {
    const userInfo = ref({})
    const form = ref({
      password: '',
      password2: ''
    })

    const getUserInfo = async () => {
      try {
        const response = await request.get('/user/info')
        if (response.code === 1) {
          userInfo.value = response.data
        } else {
          ElMessage.error(response.msg || '获取用户信息失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    const rules = {
      password: [
        { required: true, message: '请输入新密码', trigger: 'blur' }
      ],
      password2: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' }
      ]
    }

    const formRef = ref(null)

    const submitForm = async () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const response = await request.put('/user', {
              id: userInfo.value.id,
              password: form.value.password,
              password2: form.value.password2
            })
            if (response.code === 1) {
              ElMessage.success('密码重置成功')
              // 重置表单
              resetForm()
            } else {
              ElMessage.error(response.msg || '密码重置失败')
            }
          } catch (error) {
            ElMessage.error('服务异常')
          }
        } else {
          ElMessage.error('请检查输入')
          return false
        }
      })
    }

    const resetForm = () => {
      formRef.value.resetFields()
    }

    onMounted(() => {
      getUserInfo()
    })

    return {
      form,
      rules,
      formRef,
      submitForm,
      resetForm
    }
  }
}
</script>

<template>
  <div class="reset-password-container">
    <h2>重置密码</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="新密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入新密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password2">
        <el-input v-model="form.password2" type="password" placeholder="请再次输入新密码" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.reset-password-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 20px;
  margin-top: 20px;
  margin-left: 20px;
    height: 70vh;
}

.el-form {
  width: 100%;
  max-width: 400px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-button {
  margin-right: 10px;
}
</style>